﻿
<div class="top-menu-names">
    @foreach (var item in MenuItems)
    {
        if (item != MenuItems.FirstOrDefault())
        {
            <span>-></span>
        }
        <span class="menu-name">@item.Text</span>
    }
</div>


@code {

    private List<MenuItem> MenuItems = new List<MenuItem>();

    [Inject]
    private IBlazorWorkContext workContext { set; get; }

    [Inject]
    private NavigationManager navigationManager { set; get; }

    [Inject]
    private IJSRuntime _jSRuntime { set; get; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await _jSRuntime.InvokeVoidAsync("$.bb_set_menuString", DotNetObjectReference.Create(this));
            MenuItems=new List<MenuItem>();
            var CurrentPageUrl = navigationManager.Uri.Replace(navigationManager.BaseUri, "/");
            GetMenu(CurrentPageUrl, workContext.MenuItems);
            await InvokeAsync(StateHasChanged);
        }
    }

    [JSInvokable]
    public void RefreshMenuString()
    {
        MenuItems=new List<MenuItem>();
        GetMenu(workContext.CurrentPageUrl, workContext.MenuItems);
        StateHasChanged();
    }

    private MenuItem GetMenu(string Url, IEnumerable<MenuItem> menuItems)
    {
        if (menuItems==null)
        {
            return null;
        }
        MenuItem menuItem = null;
        foreach (var item in menuItems)
        {
            if (item.Url == Url)
            {
                MenuItems.Insert(0, item);
                return item;
            }
            menuItem = GetMenu(Url, item.Items);
            if (menuItem != null)
            {
                MenuItems.Insert(0, item);
                return menuItem;
            }
        }
        return menuItem;
    }

}
